package com.weichai.app.views.cityselect.view;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.github.stuxuhai.jpinyin.PinyinException;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.weichai.app.R;
import com.weichai.app.bean.CityEntity;
import com.weichai.app.page.home.adapter.CitySelectAdapter;
import com.weichai.app.views.cityselect.item.CustomItemDecoration;
import com.weichai.app.views.cityselect.model.CityInfoModel;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class CitySelectView extends ConstraintLayout {
    //views
    private RecyclerView mainRecyclerView;
    private FastIndexView indexSideView;
    private TextView indexView;

    //data and model
    //主要用于展示数据的list
    private List<CityInfoModel> list;
    //第一次加载之后缓存的数据
    private List<CityInfoModel> cacheList;

    //布局管理器
    private LinearLayoutManager layoutManager;

    private Context mContext;

    //定时器
    private Timer timer;
    //定时任务
    private TimerTask timerTask;

    //记录是否绑定过数据
    private boolean hasBindData = false;
    private CitySelectAdapter citySelectAdapter;
    private OnClickListener onClickListener;

    public CitySelectView(Context context) {
        this(context, null, 0);
    }

    public CitySelectView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CitySelectView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        mContext = context;

        View.inflate(context, R.layout.layout_city_select_view, this);

        //读取xml属性 todo

        initView();

        initAdapter();

        initListener();
    }

    private void initView() {
        mainRecyclerView = findViewById(R.id.recyclerView);
        indexSideView = findViewById(R.id.fastIndexView);
        indexView = findViewById(R.id.tv_index);
    }

    private void initAdapter() {
        list = new ArrayList<>();
        cacheList = new ArrayList<>();

        layoutManager = new LinearLayoutManager(mContext);
        mainRecyclerView.setLayoutManager(layoutManager);
        mainRecyclerView.addItemDecoration(new CustomItemDecoration(mContext, new CustomItemDecoration.TitleDecorationCallback() {
            @Override
            public String getGroupId(int position) {
                //这个是用来比较是否是同一组数据的
                return list.get(position).getSortId();
            }

            @Override
            public String getGroupName(int position) {
                CityInfoModel cityInfoModel = list.get(position);
                if (cityInfoModel.getType() == CityInfoModel.TYPE_CURRENT || cityInfoModel.getType() == CityInfoModel.TYPE_HOT) {
                    return cityInfoModel.getSortName();
                }
                //拼音都是小写的
                return cityInfoModel.getSortId().toUpperCase();
            }
        }));
        citySelectAdapter = new CitySelectAdapter();
        mainRecyclerView.setAdapter(citySelectAdapter);
        citySelectAdapter.setNewInstance(list);
    }

    private void initListener() {
        mainRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                //判断是当前layoutManager是否为LinearLayoutManager
                // 只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
                if (layoutManager instanceof LinearLayoutManager) {
                    LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
                    //获取最后一个可见view的位置
                    int lastItemPosition = linearManager.findLastVisibleItemPosition();
                    //获取第一个可见view的位置
                    int firstItemPosition = linearManager.findFirstVisibleItemPosition();
                    CityInfoModel cityInfoModel = list.get(firstItemPosition);
                    indexSideView.setLetter(cityInfoModel.getSortId().toUpperCase());
                }
            }
        });
        indexSideView.setListener(new FastIndexView.OnLetterUpdateListener() {
            @Override
            public void onLetterUpdate(String letter) {
                indexView.setText(letter);
                indexView.setVisibility(View.VISIBLE);

                moveToLetterPosition(letter);

                if (timer != null) {
                    timer.cancel();
                    timer = null;
                }

                if (timerTask != null) {
                    timerTask.cancel();
                    timerTask = null;
                }
                timerTask = new TimerTask() {
                    @Override
                    public void run() {
                        ((Activity) mContext).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                indexView.setVisibility(View.GONE);
                            }
                        });
                    }
                };
                timer = new Timer();
                timer.schedule(timerTask, 500);
            }
        });

        citySelectAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (null != onClickListener) {
                CityInfoModel cityInfoModel = (CityInfoModel) adapter.getData().get(position);
                onClickListener.onItemClick(cityInfoModel.getCityName());
            }
        });
    }

    public void setOnClickListener(OnClickListener onClickListener) {
        this.onClickListener = onClickListener;
    }

    public void setLocationCity(List<CityEntity> allCity, CityEntity currentCity) {
        if (currentCity != null) {
            list.set(0, new CityInfoModel(CitySelectAdapter.CURRENT_CITY, currentCity.wechatName, "", "", null));
        }
        citySelectAdapter.notifyItemChanged(0);
    }

    public interface OnClickListener {
        void onItemClick(String name);
    }

    /**
     * 给View绑定数据
     *
     * @param allCity     所有城市列表
     * @param currentCity 当前城市
     */
    public void bindData(List<CityEntity> allCity, CityEntity currentCity) {
        if (allCity != null) {
            for (CityEntity cityEntity : allCity) {
                if (TextUtils.isEmpty(cityEntity.wechatName)) {
                    continue;
                }
                try {
                    String pingYin = PinyinHelper.convertToPinyinString(cityEntity.wechatName, " ", PinyinFormat.WITHOUT_TONE);
                    cacheList.add(new CityInfoModel(CitySelectAdapter.CITY, cityEntity.wechatName, pingYin.substring(0, 1), pingYin, null));
                } catch (PinyinException e) {
                    e.printStackTrace();
                }
            }
            //排序
            Collections.sort(cacheList, new Comparator<CityInfoModel>() {
                @Override
                public int compare(CityInfoModel o1, CityInfoModel o2) {
                    return o1.getSortName().compareTo(o2.getSortName());
                }
            });

            if (currentCity != null)
                cacheList.add(0, new CityInfoModel(CitySelectAdapter.CURRENT_CITY, currentCity.wechatName, "", "", null));

            this.list.clear();
            this.list.addAll(cacheList);
            citySelectAdapter.notifyDataSetChanged();
            hasBindData = true;
        }
    }

    //滚动recyclerview
    private void moveToLetterPosition(String letter) {
        //这里主要是为了跳转到最顶端
        if ("#".equals(letter)) {
            letter = "*";
        }
        for (int i = 0; i < list.size(); i++) {
            CityInfoModel cityInfoModel = list.get(i);
            if (cityInfoModel.getSortId().toUpperCase().equals(letter)) {
                layoutManager.scrollToPositionWithOffset(i, 0);
                return;
            }
        }
    }
}
